
哈囉大家~
今天我們來聊聊一個看似簡單但總是讓人「啊啊啊!」的經典題目:「Rotate Array」~
也就是說,我們要把陣列裡的數字轉來轉去!
這題一看就覺得好像沒什麼,轉幾圈不就好啦?但其實內部的邏輯還是有點小巧思的!
🤓 當然啦,我們不是要你暴力地轉很多次,而是要用聰明的方式一次到位,這樣才是工程師的浪漫~ 💡❤️
難度:Medium
主題:Array, Two Pointers
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Example 1:
nums = [1,2,3,4,5,6,7], k = 3
[5,6,7,1,2,3,4]
[7,1,2,3,4,5,6]
[6,7,1,2,3,4,5]
[5,6,7,1,2,3,4]
Example 2:
nums = [-1,-100,3,99], k = 2
[3,99,-1,-100]
[99,-1,-100,3]
[3,99,-1,-100]
給定一個整數數組 nums,將數組向右旋轉 k 步,其中 k 是非負數。
範例 1:
nums = [1,2,3,4,5,6,7], k = 3
[5,6,7,1,2,3,4]
[7,1,2,3,4,5,6]
[6,7,1,2,3,4,5]
[5,6,7,1,2,3,4]
範例 2:
nums = [-1,-100,3,99], k = 2
[3,99,-1,-100]
[99,-1,-100,3]
[3,99,-1,-100]
function rotate(nums: number[], k: number): void {
  // Step 1: Reduce k if it's greater than the array length
  k = k % nums.length;
  // Step 2: Reverse the entire array
  reverse(nums, 0, nums.length - 1);
  // Step 3: Reverse the first k elements
  reverse(nums, 0, k - 1);
  // Step 4: Reverse the remaining elements
  reverse(nums, k, nums.length - 1);
}
function reverse(arr: number[], start: number, end: number): void {
  while (start < end) {
    // Swap elements
    [arr[start], arr[end]] = [arr[end], arr[start]];
    start++;
    end--;
  }
}
這題的核心思路是運用「反轉法」,這個小技巧讓我們不用笨笨地一個個轉,而是一次搞定所有位置。具體步驟如下:
希望你們今天的腦袋也能這樣「靈光一轉」,和數字一樣轉出好運!有問題隨時留言哦~我們下次見!🚀